#include "stdafx.h"
#include "d3dspriter.h"

using namespace D3DMath;

namespace D3DUtil {

Spriter::Spriter() {
	buffer = new SpriteVertex[MAXBUFFERSIZE];
}

Spriter::~Spriter() {
	delete [] buffer;
	buffer = 0;
}

void Spriter::Begin(LPDIRECT3DTEXTURE9 tex) {
	idx = 0;
	D3DBase::GetDevice()->SetTexture(0, tex);
}

void Spriter::End() {
	D3DBase::GetDevice()->SetFVF(SPRITEFVF);
	D3DBase::GetDevice()->DrawPrimitiveUP(D3DPT_TRIANGLELIST, idx/3, buffer, sizeof(SpriteVertex));	
}

void Spriter::DrawSubUV(
	float x, float y, float z, float width, float height,
	float u1, float v1, float u2, float v2, unsigned int diffuse) {
	buffer[idx].pos = Vec3(x,y,z);
	buffer[idx].diffuse = diffuse;
	buffer[idx].u = u1; buffer[idx].v = v1;

	buffer[idx+1].pos = Vec3(x+width,y,z);
	buffer[idx+1].diffuse = diffuse;
	buffer[idx+1].u = u2; buffer[idx+1].v = v1;

	buffer[idx+2].pos = Vec3(x,y+height,z);
	buffer[idx+2].diffuse = diffuse;
	buffer[idx+2].u = u1; buffer[idx+2].v = v2;

	buffer[idx+3].pos = Vec3(x+width,y+height,z);
	buffer[idx+3].diffuse = diffuse;
	buffer[idx+3].u = u2; buffer[idx+3].v = v2;

	buffer[idx+4] = buffer[idx+2];
	buffer[idx+5] = buffer[idx+1];
	idx += 6;
}

void Spriter::Draw(float x, float y, float z, float width, float height, unsigned int diffuse) {
	DrawSubUV(x,y,z,width,height,0.0f,0.0f,1.0f,1.0f,diffuse);
}

void Spriter::DrawCentered(float x, float y, float z, float width, float height, unsigned int diffuse) {
	Draw(x-width/2, y-height/2, z, width, height);
}

}